package com.ssm_basic.egweibo2.base.exception;

import com.ssm_basic.egweibo2.base.response.CodeMsg;
import com.ssm_basic.egweibo2.base.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String data = e.getFieldError().getDefaultMessage();
        return new JsonResult(CodeMsg.VALIDATED_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult handlerConstraintViolationException(ConstraintViolationException e){
        String data = e.getMessage().split(": ")[1];
        return new JsonResult(CodeMsg.VALIDATED_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult handerRuntimeException(RuntimeException e){
        log.debug("RuntimeException：" + e.getMessage());
        return new JsonResult(CodeMsg.NOT_LOGIN,e.getMessage());
    }

}
